package com.oinux.playhelper.db;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.oinux.playhelper.entity.AppInfo;
import com.oinux.playhelper.entity.AppStat;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

	private static final String DATABASE_NAME = "playhelper.db";
	private static final int DATABASE_VERSION = 1;

	private Dao<AppInfo, Integer> appInfoDao = null;
	private Dao<AppStat, Integer> appStatDao = null;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	/**
	 * 创建SQLite数据库
	 */
	@Override
	public void onCreate(SQLiteDatabase sqliteDatabase,
			ConnectionSource connectionSource) {
		try {
			TableUtils.createTable(connectionSource, AppInfo.class);
			TableUtils.createTable(connectionSource, AppStat.class);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Unable to create datbases",
					e);
		}
	}

	/**
	 * 更新SQLite数据库
	 */
	@Override
	public void onUpgrade(SQLiteDatabase sqliteDatabase,
			ConnectionSource connectionSource, int oldVer, int newVer) {
		try {
			TableUtils.dropTable(connectionSource, AppInfo.class, true);
			TableUtils.dropTable(connectionSource, AppStat.class, true);
			onCreate(sqliteDatabase, connectionSource);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(),
					"Unable to upgrade database from version " + oldVer
							+ " to new " + newVer, e);
		}
	}

	public Dao<AppInfo, Integer> getAppInfoDao() throws SQLException {
		if (appInfoDao == null) {
			appInfoDao = getDao(AppInfo.class);
		}
		return appInfoDao;
	}
	
	public Dao<AppStat, Integer> getAppStatDao() throws SQLException {
		if (appStatDao == null) {
			appStatDao = getDao(AppStat.class);
		}
		return appStatDao;
	}

}